#!/usr/bin/env python
# -*- encoding: utf-8 -*-
'''
@NAME          : avatar_service.py
@TIME          : 2025/03/05 14:30:00
@AUTHOR        : chenlip
@VERSION       : 0.1.0
@DESCRIPTION   : 用户头像服务模块，提供头像上传、删除等功能
'''

import os
import uuid
import imghdr

from typing import Dict, Tuple, Union
from flask import current_app
from app.middlewares.error_handler import BusinessError, service_exception


class AvatarService:
    """用户头像服务类，提供头像上传、删除等功能"""
    
    # 默认头像路径
    DEFAULT_AVATAR = '/static/avatar/d_logo.jpg'
    
    @classmethod
    def upload_avatar(cls, file, user_id: int) -> Dict:
        """
        上传用户头像
        
        Args:
            file: 上传的文件对象
            user_id: 用户ID
            
        Returns:
            Dict: 上传结果
                {
                    "success": True/False,
                    "message": "操作结果描述",
                    "data": {
                        "avatar_url": "/static/avatar/2022-02-26/123456.jpg"
                    }
                }
        """
        try:
            
            
            # 创建保存目录
            today = current_app.config['CURDAY']
            save_dir = os.path.join(current_app.root_path, 'static', 'avatar', today)
            
            
            # 确保目录存在
            os.makedirs(save_dir, exist_ok=True)
            
            # 生成唯一文件名
            print(f'save_dir: {save_dir}/{file.filename}; user_id: {user_id}')
            extension = file.filename.rsplit('.', 1)[1].lower()
            unique_filename = f"{user_id}_{uuid.uuid4().hex[:8]}.{extension}"
            
            # 保存文件
            file_path = os.path.join(save_dir, unique_filename)
            file.save(file_path)
            
            # 生成相对URL路径
            avatar_url = f"/static/avatar/{today}/{unique_filename}"
            
            return {
                "success": True,
                "message": "头像上传成功",
                "data": {
                    "avatar_url": avatar_url
                }
            }
            
        except Exception as e:
            current_app.logger.error(f"上传头像异常: {str(e)}")
            return {
                "success": False,
                "message": f"头像上传失败: {str(e)}",
                "error_code": 500  # Internal Server Error
            }
    
    @classmethod
    def delete_avatar(cls, avatar_url: str) -> Dict:
        """
        删除用户头像
        
        Args:
            avatar_url: 头像URL
            
        Returns:
            Dict: 删除结果
        """
        try:
            # 如果是默认头像，无需删除
            if avatar_url == cls.DEFAULT_AVATAR:
                return {
                    "success": True,
                    "message": "无需删除默认头像",
                    "data": {
                        "avatar_url": cls.DEFAULT_AVATAR
                    }
                }
            
            # 转换为物理路径
            if avatar_url.startswith('/'):
                avatar_url = avatar_url[1:]  # 去除开头的斜杠
                
            file_path = os.path.join(current_app.root_path, avatar_url)
            
            # 删除文件
            if os.path.exists(file_path):
                os.remove(file_path)
                
            return {
                "success": True,
                "message": "头像删除成功",
                "data": {
                    "avatar_url": cls.DEFAULT_AVATAR
                }
            }
            
        except Exception as e:
            current_app.logger.error(f"删除头像异常: {str(e)}")
            return {
                "success": False,
                "message": f"删除头像失败: {str(e)}",
                "error_code": 500  # Internal Server Error
            }
    
    @classmethod
    def update_avatar(cls, file, user_id: int, old_avatar_url: str) -> Dict:
        """
        更新用户头像
        
        Args:
            file: 上传的文件对象
            user_id: 用户ID
            old_avatar_url: 旧头像URL
            
        Returns:
            Dict: 更新结果
        """
        try:
            # 先删除旧头像
            if old_avatar_url != cls.DEFAULT_AVATAR:
                cls.delete_avatar(old_avatar_url)
            
            # 上传新头像
            return cls.upload_avatar(file, user_id)
            
        except Exception as e:
            current_app.logger.error(f"更新头像异常: {str(e)}")
            return {
                "success": False,
                "message": f"更新头像失败: {str(e)}",
                "error_code": 500  # Internal Server Error
            }
